import { HttpException } from '@nestjs/common';

export const codeMap = {
  100: 'Continue',
  101: 'Switching Protocols',
  200: 'OK',
  201: 'Created',
  202: 'Accepted',
  203: 'Non-Authoritative Information',
  204: 'No Content',
  205: 'Reset Content',
  206: 'Partial Content',
  300: 'Multiple Choices',
  301: 'Moved Permanently',
  302: 'Found',
  303: 'See Other',
  304: 'Not Modified',
  305: 'Use Proxy',
  307: 'Temporary Redirect',
  400: 'Bad Request',
  401: 'Unauthorized',
  402: 'Payment Required',
  403: 'Forbidden',
  404: 'Not Found',
  405: 'Method Not Allowed',
  406: 'Not Acceptable',
  407: 'Proxy Authentication Required',
  408: 'Request Time-out',
  409: 'Conflict',
  410: 'Gone',
  411: 'Length Required',
  412: 'Precondition Failed',
  413: 'Request Entity Too Large',
  414: 'Request-URI Too Large',
  415: 'Unsupported Media Type',
  416: 'Requested range not satisfiable',
  417: 'Expectation Failed',
  418: "I'm a teapot",
  500: 'Internal Server Error',
  501: 'Not Implemented',
  502: 'Bad Gateway',
  503: 'Service Unavailable',
  504: 'Gateway Time-out',
  505: 'HTTP Version not supported'
};

type Result = {
  code?: number | string; // http状态码
  data?: any; // 请求返回数据
  msg?: string; // 请求描述，多为自定义
  message?: string; // 请求信息，多为原生信息
  errMsg?: string; // 错误具体详情，原生信息或自定义
  error?: object; // 原生未处理报错信息
  tip?: string | number; // 补充信息，多为小提示
  accessToken?: string; // 访问令牌
  refreshToken?: string; // 刷新令牌
  total?: number; // 总条数
  pageNum?: number; // 当前页码
  pageSize?: number; // 每页条数
  pages?: number; // 总页数
  codeExp?: string; // http状态码文本含义
  success?: boolean; // 请求是否成功
  timestamp?: number; // 请求时间
  costtime?: number; // 请求耗时
};

export function useResult(res: Result) {
  const defaultRes = {
    code: 200
  };

  const result = Object.assign(defaultRes, res);

  // 统一预置参数
  if (!result.msg) result.msg = codeMap[result.code];
  result.codeExp = codeMap[result.code];
  result.success = String(result.code).startsWith('2');
  result.timestamp = Date.now();

  if (!result.success) {
    // 正规党，非200党，以httpStatusCode抛出异常
    throw new HttpException(result, result.code);
  }

  return result;
}
